/*
 * All rights Reserved, Designed By DataDriver
 * Copyright:    DataDriver.Inc
 * Company:      Zhuo Wo Infomation Technology (ShangHai) CO.LTD
 */
package com.sun.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.*;
import org.springframework.util.StringValueResolver;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;


/**
 * 按照业务需求动态的切换配置信息
 * <p>
 * 例如多数据源的操作
 * <p>
 * <p>
 * EmbeddedValueResolverAware值解析器
 *
 *
 * @Profile("dev")  加了环境标识的Bean只有当环境被激活时才会被创建
 * @Profile("default") 加了default默认的环境是激活状态的
 */

@Configuration
@ComponentScan("com.sun")
@PropertySource("classpath:/db.properties")
public class ProfileConfig implements EmbeddedValueResolverAware {


    //赋值操作
    private StringValueResolver stringValueResolver;


    @Value("${db.username}")
    private String user;
    @Value("${db.password}")
    private String pwd;

    private String driverClass;


    //开发数据源
    @Bean
    @Profile("dev")
    public DataSource dataSourceDev() throws Exception {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(pwd);
        dataSource.setJdbcUrl("jdbc:mysql://150.158.163.91:3306/datasources_1");
        //值解析器获取配置文件中的信息
        dataSource.setDriverClass(driverClass);
        return dataSource;
    }

    //生产数据源
    @Bean
    @Profile("pro")
    public DataSource dataSourcePro() throws Exception {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(pwd);
        dataSource.setJdbcUrl("jdbc:mysql://150.158.163.91:3306/datasources_2");
        dataSource.setDriverClass(driverClass);
        return dataSource;
    }

    //生产数据源
    @Bean
    @Profile("default")
    public DataSource dataSourceDefault() throws Exception {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(pwd);
        dataSource.setJdbcUrl("jdbc:mysql://150.158.163.91:3306/my-cloud");
        dataSource.setDriverClass(driverClass);
        return dataSource;
    }

    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        this.stringValueResolver = resolver;
        driverClass = stringValueResolver.resolveStringValue("${db.className}");
    }
}
